package cn.edu.ctbu.api01.restcontroller;

import ch.qos.logback.classic.Logger;
import cn.edu.ctbu.api01.domain.Student;
import cn.edu.ctbu.api01.helper.PageUtils;
import cn.edu.ctbu.api01.helper.Result;
import cn.edu.ctbu.api01.helper.ResultUtil;
import cn.edu.ctbu.api01.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value="/api/student")  /**通用地址前缀**/
/**
 * 产生日志，log
 */
@Slf4j


public class StudentRestController {
    @Autowired
    private StudentService studentService;


    @GetMapping(value="/list")
    public List<Student> GetAll(){

        return studentService.findAll();
    }
    @GetMapping(value="/list3")
    public PageUtils GetAll(Integer pageNum, Integer pageSize){
        Pageable pageable=PageRequest.of(pageNum-1, pageSize);
        //服务器端分页
        Page<Student> tempStudents=studentService.findAll(pageable);
        //格式转化
        PageUtils pageUtils=new PageUtils(tempStudents.getTotalElements(),tempStudents.getContent());
        return pageUtils;
    }
    /**
     * 验证并增加学生
     * @param student
     * @return
     */
    @PostMapping(value="/add")
    public Result<Student> add(@Valid Student student, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            Result.error(bindingResult.getFieldError().getDefaultMessage());
        }
        studentService.insert(student);
        return ResultUtil.success(student);
    }
    /**
     * 读取--url:/api/student/get/id
     * @return
     */
    @GetMapping(value="/get/{id}")
    public Student get(@PathVariable Integer id){
        Student student = studentService.findById(id);
        student.setPassword("");
        return student;
    }
    /**
     * 示例：http://localhost:8080/api/student/getbyid/4
     * 其中  4  表示 id
     * @param id
     * @return
     */
    @GetMapping(value="/getbyid/{id}")
    public Student GetById(@PathVariable Integer id){
        return studentService.findById(id);
    }
    /**
     * * 示例：http://localhost:8080/api/student/getbyname/李玲
     * @param name
     * @return
     */
    @GetMapping(value="/getbyname/{name}")
    public List<Student> GetByName(@PathVariable String name){
        return studentService.findByName(name);
    }
    /**
     * 根据 id删除
     * @param id
     * @return
     */
    @DeleteMapping(value="deletebyid/{id}")
    public Result DeleteById(@PathVariable Integer id){

        studentService.deleteById(id);
        return ResultUtil.success();
    }
    /**
     * 增加学生
     * @param student
     * @return
     */
    @PostMapping(value="/add1")
    public Integer Add(@RequestBody Student student){
        studentService.insert(student);
        return student.getId();
    }
    /**
     * 更新学生的方法
     * @param student
     * @return
     */
    @PutMapping(value="/update")
    public Result<Student> update(@RequestBody @Valid Student student, BindingResult bindingResult){
        // 读取旧数据
        Student oldstudent = studentService.findById(student.getId());
        if(StringUtils.isEmpty(student.getPassword())){
            // 如果没有新密码，就使用旧密码
            student.setPassword(oldstudent.getPassword());
        }
        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return Result.error(bindingResult.getFieldError().getDefaultMessage());
        }
        student=studentService.update(student);
        return ResultUtil.success(student);
    }

    /**
     * 增加学生的方法
     * @param student
     * @return
     */
    @PostMapping(value="/insert")
    public Result<Student> insert(@RequestBody @Valid Student student, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return Result.error(bindingResult.getFieldError().getDefaultMessage());
        }
        student=studentService.insert(student);
        return ResultUtil.success(student);
    }
    /**
     * 删除学生的方法
     * @param student
     */
    @DeleteMapping(value="/delete")
    public Result<Student> delete(@RequestBody @Valid Student student, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return Result.error(bindingResult.getFieldError().getDefaultMessage());
        }
        studentService.delete(student);
        return ResultUtil.success(student);
    }

    /**
     * 查询学生
     * @param no
     * @param name
     * @param sex
     * @param ageRange
     * @param scoreRange
     * @return
     */
    @GetMapping(value="/search")
    public List<Student> searchStudents(
            @RequestParam(required = false) String no,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer sex,
            @RequestParam(required = false) String ageRange,
            @RequestParam(required = false) String scoreRange
    ) {
        return studentService.searchStudents(no, name, sex, ageRange, scoreRange);
    }
    @GetMapping(value="/login")
    public Result login(String username, String password) throws Exception{
        studentService.validUserNameAndPassword(username,password);
        return Result.ok();
    }
}
